#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.dev'

import django
django.setup()

import time, json, datetime, requests
from django.conf import settings

from vouchers.models import AliDiscountCouponInfo, AliDiscountCouponBillDetails, AliFundTransfer
from vouchers.utils import AlipayOpen
from customers.utils import favor_query_coupons, favor_query_coupons_sichun
from activities.models import Channel
from equity_mall.utils.wash_level1 import haizhui_get_sign


def synchronous_coupons_status():
    '''同步支付宝优惠券核销情况'''
    print('%s: synchronous_coupons_status' % time.ctime())
    today = datetime.datetime.now()
    vouchers = AliDiscountCouponInfo.objects.filter(status__in=[1, 8, 9, 11], alidiscountcoupon__coupon_channel=1)
    alipayopen = AlipayOpen()
    l1 = []
    for voucher in vouchers:
        activityinfo = voucher.alidiscountcoupon
        if activityinfo.platform_id != 1:
            continue
        if voucher.status == 9 and voucher.gmt_expired >= today:
            continue
        result = json.loads(alipayopen.voucherquery(voucher.voucher_id))
        if result['status'] == 'USED':
            activityinfo.use_count += 1
            activityinfo.save()
            l1.append(voucher.voucher_id)
            try:
                if 'bill_details' in result:
                    for bill_datail in result['bill_details']:
                        voucher.gmt_use = bill_datail['gmt_create']
                        bill_datail['voucherinfo_id'] = voucher.id
                        bill_datail.pop('extend_info')
                        AliDiscountCouponBillDetails.objects.create(**bill_datail)
            except:
                pass
            try:
                alidiscountcoupon_level = voucher.alidiscountcoupon_level
                alidiscountcoupon_level.use_number += 1
                alidiscountcoupon_level.p_use_number += 1
                alidiscountcoupon_level.save()
                relation_set = alidiscountcoupon_level.child_set.all()
                for relation in relation_set:
                    parent = relation.parent
                    parent.p_use_number += 1
                    parent.save()
            except:
                pass
        voucher.status = voucher.STATUS_ENUM[result['status']]
        voucher.save()
    print(l1)
    return l1


def synchronous_wx_coupons_status(id_list=None):
    '''同步微信优惠券核销情况'''
    print('%s: synchronous_coupons_status' % time.ctime())
    vouchers = AliDiscountCouponInfo.objects.filter(status__in=[1, 8, 9], alidiscountcoupon__coupon_channel=2).exclude(alidiscountcoupon__distribution_platform_id__in=[5,6])
    if id_list:
        vouchers = vouchers.filter(id__in=id_list)
    l1 = []
    Appkey = 'SN8958632086'
    AppSeret = 'DBXRZYRVZUI2CTGQOXPOOEVYUCG7Z4XT'
    for voucher in vouchers:
        activityinfo = voucher.alidiscountcoupon
        coupon_id = voucher.voucher_id
        # openid = voucher.user_id
        # appid = 'wx6b0076ae2d2cb49b'
        try:
            if voucher.appid:
                openid = voucher.user_id
                appid = voucher.appid
            else:
                if voucher.customer_user.new_openid:
                    appid = settings.CUSTOMER_APP_ID_NEW
                    openid = voucher.customer_user.new_openid
                else:
                    appid = settings.CUSTOMER_APP_ID
                    openid = voucher.customer_user.openid
        except:
            print(voucher.id)
            continue
        if activityinfo.platform_id == 13:
            distribute_channel = Channel.objects.get(id=13)
        else:
            distribute_channel = Channel.objects.get(id=9)
        result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
        try:
            if result['status'] == 'USED':
                activityinfo.use_count += 1
                activityinfo.save()
                l1.append(voucher.voucher_id)
                try:
                    if 'bill_details' in result:
                        for bill_datail in result['bill_details']:
                            voucher.gmt_use = bill_datail['gmt_create']
                            bill_datail['voucherinfo_id'] = voucher.id
                            AliDiscountCouponBillDetails.objects.create(**bill_datail)
                except:
                    pass
                try:
                    alidiscountcoupon_level = voucher.alidiscountcoupon_level
                    alidiscountcoupon_level.use_number += 1
                    alidiscountcoupon_level.p_use_number += 1
                    alidiscountcoupon_level.save()
                    relation_set = alidiscountcoupon_level.child_set.all()
                    for relation in relation_set:
                        parent = relation.parent
                        parent.p_use_number += 1
                        parent.save()
                except:
                    pass
                voucher.status = 7
                voucher.gmt_use = datetime.datetime.now()
                try:
                    if vouchers.companyuser_id == 65449 and vouchers.notify_url:
                        headers = {"User-Agent": "PostmanRuntime/7.28.2"}
                        timestamp = int(time.time()*1000)
                        sign_data = {}
                        sign_data['order_no'] = vouchers.out_biz_order
                        sign_data['supplier_no'] = Appkey
                        sign_data['status'] = 'VERIFIED_OFF'
                        sign_data['timestamp'] = str(timestamp)
                        sign = haizhui_get_sign(sign_data, AppSeret)
                        url = f'{vouchers.notify_url}?order_no={vouchers.out_biz_order}&supplier_no={Appkey}&status=VERIFIED_OFF&sign={sign}&timestamp={timestamp}'
                        print(url)
                        # response = requests.request('get', url=url)
                        response = requests.get(url=url, headers=headers)
                        content = response.text
                        if content != "OK":
                            time.sleep(5)
                            response = requests.get(url=url, headers=headers)
                            content = response.text
                            if content != "OK":
                                time.sleep(5)
                                response = requests.get(url=url, headers=headers)
                        print(response.status_code)
                        print(response.content)
                except:
                    pass
                try:
                    if vouchers.companyuser_id == 65448 and vouchers.notify_url:
                        request_data = {}
                        request_data['code'] = 200
                        request_data['message'] = '券核销'
                        request_data['err_code_des'] = ''
                        request_data['out_biz_no'] = vouchers.out_biz_order
                        request_data['create_time'] = vouchers.gmt_distributed.strftime('%Y-%m-%d %H:%M:%S')
                        request_data['expired_time'] = vouchers.gmt_expired.strftime('%Y-%m-%d %H:%M:%S')
                        request_data['use_time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                        request_data['status_display'] = '已核销'
                        request_data['total_amount'] = vouchers.total_amount
                        request_data['voucher_id'] = coupon_id
                        headers = {'Content-Type': 'application/json'}
                        response = requests.request('post', url=vouchers.notify_url, data=json.dumps(request_data), headers=headers)
                        print(response.status_code)
                except:
                    pass
            elif result['status'] == 'EXPIRED':
                voucher.status = 12
            voucher.save()
        except:
            pass
    print(l1)
    return l1


def synchronous_pay_date():
    '''同步优惠券核销情况'''
    print('%s: synchronous_pay_date' % time.ctime())
    queryset = AliFundTransfer.objects.filter(pay_date__isnull=True)
    alipayopen = AlipayOpen()
    l1 = []
    for query in queryset:
        order_id = query.order_id
        result = json.loads(alipayopen.transunitransferquery(order_id))
        if result['status'] == 'SUCCESS':
            l1.append(order_id)
            query.trans_state = 2
            query.pay_date = result['pay_date']
            query.save()
    print(l1)
    return l1


if __name__ == '__main__':
    synchronous_wx_coupons_status()
    # alipayopen = AlipayOpen()
    # result = json.loads(alipayopen.voucherquery('202210090007300230230C4YZ6OI'))
    # print(result)
